import '../models/fishing_technique.dart';
import '../models/comment.dart';
import 'http_client.dart';

class TechniqueService {
  final HttpClient _httpClient = HttpClient();

  /// 通用数据提取方法，适配不同的后端返回格式
  dynamic _extractData(Map<String, dynamic> responseData) {
    // 如果有data字段，优先使用data
    if (responseData.containsKey('data') && responseData['data'] != null) {
      return responseData['data'];
    }
    // 如果有rows字段，使用rows
    if (responseData.containsKey('rows') && responseData['rows'] != null) {
      return responseData['rows'];
    }
    // 否则直接返回整个响应数据
    return responseData;
  }

  /// 获取钓技文章列表
  Future<Map<String, dynamic>> getTechniqueList({
    int pageNum = 1,
    int pageSize = 10,
    String? title,
    String? category,
    String? difficulty,
  }) async {
    try {
      final Map<String, dynamic> params = {
        'pageNum': pageNum,
        'pageSize': pageSize,
      };
      
      if (title != null && title.isNotEmpty) {
        params['title'] = title;
      }
      if (category != null && category.isNotEmpty && category != '全部') {
        params['category'] = category;
      }
      if (difficulty != null && difficulty.isNotEmpty && difficulty != 'all') {
        params['difficulty'] = difficulty;
      }

      final response = await _httpClient.get(
        '/pond/app/fishing/technique/list',
        queryParameters: params,
      );

      final data = _extractData(response);
      final total = response['total'] ?? 0;
      
      return {
        'total': total,
        'techniques': (data as List)
            .map((json) => FishingTechnique.fromJson(json))
            .toList(),
      };
    } catch (e) {
      rethrow;
    }
  }

  /// 获取钓技文章详情
  Future<FishingTechnique> getTechniqueDetail(String id) async {
    try {
      final response = await _httpClient.get('/pond/app/fishing/technique/$id');

      final data = _extractData(response);
      return FishingTechnique.fromJson(data);
    } catch (e) {
      rethrow;
    }
  }

  /// 点赞/取消点赞文章
  Future<Map<String, dynamic>> toggleLike(String id) async {
    try {
      final response = await _httpClient.post('/pond/app/fishing/technique/$id/like');

      final data = _extractData(response);
      return data is Map<String, dynamic> ? data : response;
    } catch (e) {
      rethrow;
    }
  }

  /// 收藏/取消收藏文章
  Future<Map<String, dynamic>> toggleFavorite(String id) async {
    try {
      final response = await _httpClient.post('/pond/app/fishing/technique/$id/favorite');

      final data = _extractData(response);
      return data is Map<String, dynamic> ? data : response;
    } catch (e) {
      rethrow;
    }
  }

  /// 增加文章阅读量
  Future<int> incrementReadCount(String id) async {
    try {
      final response = await _httpClient.post('/pond/app/fishing/technique/$id/read');

      final data = _extractData(response);
      if (data is Map<String, dynamic> && data['readCount'] != null) {
        return data['readCount'];
      }
      return 0; // 默认返回0
    } catch (e) {
      rethrow;
    }
  }

  /// 获取文章评论列表
  Future<Map<String, dynamic>> getComments(String techniqueId, {
    int pageNum = 1,
    int pageSize = 10,
  }) async {
    try {
      final response = await _httpClient.get(
        '/pond/app/fishing/technique/$techniqueId/comments',
        queryParameters: {
          'pageNum': pageNum,
          'pageSize': pageSize,
        },
      );

      final data = _extractData(response);
      final total = response['total'] ?? 0;
      
      // 保持嵌套结构，不展开为平级
      return {
        'total': total,
        'comments': (data as List)
            .map((json) => Comment.fromJson(json))
            .toList(),
      };
    } catch (e) {
      rethrow;
    }
  }

  /// 发表评论
  Future<Map<String, dynamic>> addComment(String techniqueId, String content, {String? parentId}) async {
    try {
      final Map<String, dynamic> requestData = {
        'content': content,
      };
      
      if (parentId != null) {
        requestData['parentId'] = parentId;
      }

      final response = await _httpClient.post(
        '/pond/app/fishing/technique/$techniqueId/comment',
        data: requestData,
      );

      // 返回标准格式的响应
      return {
        'success': true,
        'message': response['msg'] ?? '评论成功',
        'data': response['data'],
      };
    } catch (e) {
      return {
        'success': false,
        'message': '发表评论失败: $e',
        'data': null,
      };
    }
  }

  /// 删除评论
  Future<void> deleteComment(String commentId) async {
    try {
       await _httpClient.delete('/pond/app/fishing/technique/comment/$commentId');
      // 删除操作通常只需要检查HTTP状态码，不需要特殊处理返回数据
    } catch (e) {
      rethrow;
    }
  }

  /// 点赞/取消点赞评论
  Future<Map<String, dynamic>> toggleCommentLike(String commentId) async {
    try {
      final response = await _httpClient.post('/pond/app/fishing/technique/comment/$commentId/like');

      final data = _extractData(response);
      return data is Map<String, dynamic> ? data : response;
    } catch (e) {
      rethrow;
    }
  }

  /// 获取用户收藏列表
  Future<Map<String, dynamic>> getFavorites({
    int pageNum = 1,
    int pageSize = 10,
  }) async {
    try {
      final response = await _httpClient.get(
        '/pond/app/fishing/technique/favorites',
        queryParameters: {
          'pageNum': pageNum,
          'pageSize': pageSize,
        },
      );

      final data = _extractData(response);
      final total = response['total'] ?? 0;
      
      return {
        'total': total,
        'techniques': (data as List)
            .map((json) => FishingTechnique.fromJson(json))
            .toList(),
      };
    } catch (e) {
      rethrow;
    }
  }

  /// 获取热门文章
  Future<List<FishingTechnique>> getHotTechniques({
    int limit = 10,
    String type = 'read', // read, like, favorite
  }) async {
    try {
      final response = await _httpClient.get(
        '/pond/app/fishing/technique/hot',
        queryParameters: {
          'limit': limit,
          'type': type,
        },
      );

      final data = _extractData(response);
      return (data as List)
          .map((json) => FishingTechnique.fromJson(json))
          .toList();
    } catch (e) {
      rethrow;
    }
  }

  /// 获取分类列表
  Future<List<Map<String, dynamic>>> getCategories() async {
    try {
      final response = await _httpClient.get('/pond/app/fishing/technique/categories');

      final data = _extractData(response);
      return List<Map<String, dynamic>>.from(data);
    } catch (e) {
      rethrow;
    }
  }

  /// 获取热门标签
  Future<List<Map<String, dynamic>>> getHotTags({int limit = 20}) async {
    try {
      final response = await _httpClient.get(
        '/pond/app/fishing/technique/tags',
        queryParameters: {'limit': limit},
      );

      final data = _extractData(response);
      return List<Map<String, dynamic>>.from(data);
    } catch (e) {
      rethrow;
    }
  }

  /// 获取用户的钓技评论
  Future<List<Comment>> getUserComments({
    int pageNum = 1,
    int pageSize = 20,
  }) async {
    try {
      // 暂时使用现有的API，通过获取所有评论然后筛选当前用户的评论
      // 这是一个临时解决方案，等待后端提供专门的用户评论API
      
      // 先尝试调用专门的用户评论API
      try {
        final response = await _httpClient.get(
          '/pond/app/user/comments/techniques',
          queryParameters: {
            'pageNum': pageNum,
            'pageSize': pageSize,
          },
        );

        final data = _extractData(response);
        if (data is List) {
          return data.map((json) => Comment.fromJson(json)).toList();
        } else if (data is Map && data['rows'] != null) {
          return (data['rows'] as List).map((json) => Comment.fromJson(json)).toList();
        }
      } catch (apiError) {
        // 如果专门的API不存在，返回空列表
        // 在实际应用中，这里可以实现其他获取逻辑
        return [];
      }
      
      return [];
    } catch (e) {
      return []; // 返回空列表而不是抛出异常
    }
  }
}